/**
 * <b>项目名：</b>hclv-web<br/>
 * <b>包名：</b>com.flea.hclv.service.impl<br/>
 * <b>文件名：</b>HVisitorPayItemService.java<br/>
 * <b>版本信息：</b>1.0<br/>
 * <b>日期：</b>2018年11月15日 上午1:53:17<br/>
 * <b>COPYRIGHT 2010-2012 ALL RIGHTS RESERVED 虫子科技</b>-版权所有<br/>
 */
package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.HVisitorOrderMapper;
import com.flea.hclv.model.dao.HVisitorPayItemMapper;
import com.flea.hclv.model.entity.HVisitorOrder;
import com.flea.hclv.model.entity.HVisitorPayItem;
import com.flea.hclv.service.HVisitorPayItemService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.base.util.StringUtil;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @description
 * @createTime 2018年11月15日 上午1:53:17
 * @modifyTime
 * @author myflea@163.com
 * @version 1.0
 */
@Service
public class HVisitorPayItemServiceImpl implements HVisitorPayItemService {

    private Logger logger = LoggerFactory.getLogger(HVisitorPayItemServiceImpl.class);

    @Autowired
    private HVisitorPayItemMapper visitorPayItemMapper;
    @Autowired
    private HVisitorOrderMapper visitorOrderMapper;

    @Override
    public ServerResponse<HVisitorPayItem> addPayItem(HttpServletRequest request, String model) throws Exception {
        JSONObject obj = JSONObject.parseObject(model);
        String orderNo = obj.getString("orderNo");
        String userId = FleaOrgUtils.getCurrentUserDeptUuid(request);
        HVisitorOrder order = visitorOrderMapper.selectByOrderNo(orderNo);
        if (null == order) {
            logger.error("订单不存在，订单号：{}",orderNo);
            return ServerResponse.createByErrorMessage("该订单不存在");
        }
        //实际应付
        Float orderTotal = order.getTotalAmount();
        //实际已付
        Float orderPayMent = order.getPayment();

        if (orderTotal.equals(orderPayMent)) {
            logger.info("已经付款成功，请不要重复付款,订单详情：{}",order);
            return ServerResponse.createBySuccessMessage("已经付款成功，请不要重复付款");
        }
        //未付款f
        float shouldPay;
        if (orderPayMent == null||orderPayMent == 0) {
            shouldPay = orderTotal;
            orderPayMent = 0f;
        } else {
            shouldPay = orderTotal - orderPayMent;
            logger.info("订单总金额：{}，支付金额：{}，应付金额：{}",orderTotal,orderPayMent,shouldPay);
        }

        JSONArray pays = JSON.parseArray(obj.getString("pays"));
        List<HVisitorPayItem> models = Lists.newArrayList();
        for (int i = 0; i < pays.size(); i++) {
            JSONObject jsonObject = pays.getJSONObject(i);
            HVisitorPayItem item = new HVisitorPayItem();
            item.setId(FleaStringUtils.getGenerateUUID());
            item.setCreateUser(userId);
            item.setOrderNo(orderNo);
            item.setPayPlatform(jsonObject.getString("paymentType"));
            item.setPayMoney(jsonObject.getFloat("payMoney"));
            item.setPlatformNumber(jsonObject.getString("platformNumber"));
            item.setPayUser(jsonObject.getString("payUser"));
            models.add(item);
        }
        //计算金额
//		List<HVisitorPayItem> models = JSONObject.parseArray(obj.getString("pays"), HVisitorPayItem.class);

        float reqPayTotal = 0f;
//		List<HVisitorPayItem> newItems = new ArrayList<HVisitorPayItem>();
        for (HVisitorPayItem hVisitorPayItem : models) {
            reqPayTotal += hVisitorPayItem.getPayMoney();
//			hVisitorPayItem.setCreateUser(userId);
//			hVisitorPayItem.setId(FleaStringUtils.getGenerateUUID());
//			hVisitorPayItem.setModifyUser(userId);
//			newItems.add(hVisitorPayItem);
        }

        if (reqPayTotal == shouldPay) {
            order.setStatus(HConstant.D_ORDER_STATUS_PAYDONE);
            order.setPayment(orderTotal);
            order.setModifyUser(userId);
            order.setEndTime(new Date());
            logger.info("设置为付款完成,订单：{}",order);
            //付款完成，修改订单装填
        } else if (shouldPay > reqPayTotal) {
            //付款未完成，进入部分付款状态
            order.setStatus(HConstant.D_ORDER_STATUS_PARTPAY);
            order.setPayment(orderPayMent + reqPayTotal);
            order.setModifyUser(userId);
            logger.info("设置为付款为完成，进入部分付款状态，订单：{}",order);
        } else if (shouldPay < reqPayTotal) {
            order.setStatus(HConstant.D_ORDER_STATUS_PAYDONE);
            order.setPayment(orderPayMent + reqPayTotal);
            order.setModifyUser(userId);
            logger.info("设置为付款完成,订单：{}",order);
        }
        boolean result = visitorPayItemMapper.saveBatch(models) == models.size();
        if (!result) {
            logger.error("支付失败，支付记录：{}",model);
            return ServerResponse.createByErrorMessage("支付失败！");
        }
        result = visitorOrderMapper.updateByPrimaryKeySelective(order) == 1;
        if (!result) {
            logger.error("支付成功，订单状态更新失败,订单：{}",order);
            return ServerResponse.createByErrorMessage("支付成功，订单状态更新失败！");
        }
        logger.info("支付成功，更订单状态成功");
        return ServerResponse.createBySuccessMessage("支付成功");
    }

    /**
     *
     * @param orderNo
     * @return
     * @throws Exception
     */
    @Override
    public ServerResponse<List<HVisitorPayItem>> getPayListByOrderNo(String orderNo) throws Exception {
        if (StringUtil.isEmpty(orderNo)) {
            logger.error("参数非法,订单号：{}",orderNo);
            return ServerResponse.createByErrorMessage("参数非法");
        }
        List<HVisitorPayItem> result = visitorPayItemMapper.findByOrderNo(orderNo);
        logger.info("返回支付明细：{}",result);
        return ServerResponse.createBySuccess(result);
    }

}
